﻿rm(list = ls())
library(tidyverse)
gx_scr <- list.files("/Pub/Data/Code_Center/CodeLib",recursive = T,full.names = T,pattern = '\\.R$')
walk(gx_scr,~ source(.x))


rm(list = ls())
suppressMessages(library(tidyverse))
suppressMessages(library(magrittr))
scr1 <- list.files("~/Project_wangyk/Codelib_YK/some_scr", full.names = T, recursive = T, pattern = "\\.R$")
scr2 <- list.files("/Pub/Users/cuiye/RCodes/UserCode", recursive = T, full.names = T, pattern = "\\.R$")
walk(c(scr2, scr1), ~ source(.x))

# library(YK.pkg)
# conflicted::conflict_prefer_all("dplyr", quiet = T)
source("~/Project_wangyk/Codelib_YK/some_cancers/major_test2.r")

out_home <- "/Pub/Users/wangyk/project/p/2024_ann_stad/"

# 创建文件夹--------
walk(out_home, function(out_home) {
    walk(c("data", "out", "src"), ~ dir.create(path = paste0(out_home, .x), recursive = T))
    walk(c("src"), function(y) {
        walk(
            str_pad(1:12, width = 2, pad = "0") %>% str_c(., ".__.r"),
            ~ file.create(path = paste0(out_home, y, "/", .x), recursive = T)
        )
    })
    dir.create(path = paste0(out_home, "test/"), recursive = T)
    r_file_path <- list.files(path = paste0(out_home, "/src"), pattern = "\\.r$", full.names = T)

    words <- str_glue('
    rm(list = ls())

    rm(list = ls())

    suppressMessages(library(tidyverse))
    suppressMessages(library(magrittr))
    library(Seurat)

    list.files("/data/Users/cuiye/Team_Code",recursive = T,pattern = "\\.R$",full.names = T) %>% walk(~ source)

    out_home <- "{out_home}"
    setwd(out_home)')

    walk(r_file_path, ~ write_lines(x = words, file = .x))
})
# ------


# 新格式数据，验证循环---------
idata_index <- readxl::read_excel("/Pub/Data/Data_Center/idata.xlsx",sheet = 1) 
colnames(idata_index)

vali_data_name <- idata_index %>% filter(癌症名称 == 'KIRC') %>% pull(数据集名称)[1:4]
vali_full_dir <- list.files("/Pub/Data/Data_Center/GEO/v1",full.names = T,recursive = T)

coef_file <- unicox_res$lasso$coef
od <- paste0(out_home, "out/2.cluster_to_model")

vali_res <- map_dfr(vali_data_name, function(cohort_name) {

    cohort_name <- vali_data_name[10]
    message(paste0("\n\n\n>>> ", cohort_name, "\n"))

    clin_dir <- vali_full_dir[str_detect(vali_full_dir, cohort_name)][
        vali_full_dir[str_detect(vali_full_dir, cohort_name)] %>% str_detect("\\/clinical.RData")
    ]

    exprs_dir <- vali_full_dir[str_detect(vali_full_dir, cohort_name)][
        vali_full_dir[str_detect(vali_full_dir, cohort_name)] %>% str_detect("\\/expression.RData")
    ]

    clin <- load(clin_dir)
    exprs <- load(exprs_dir)

    data_list <- list("data_exprs" = get0(exprs), "data_clinical" = get0(clin))


    status_type <- c("OS", "PFS", "DFS", "DFI", "DSS", "PFI", "MFS", "RFS", "MFS", "DMFS", "TDM")
    vali_infor <- map_dfr(status_type, \(x){
        # x <- 'OS'
        time_type <- str_glue("{x}.Time") %>% as.character()
        status_type_1 <- str_glue("{x}.Status") %>% as.character()

        if (all(c(status_type_1, time_type) %in% colnames(data_list[["data_clinical"]]))) {
            cohort_name_status_type <- as.character(str_glue("{cohort_name}_{x}"))

            data_list[["data_clinical"]] <- data_list[["data_clinical"]] %>%
                rename("time" = as.character(str_glue("{x}.Time")), "status" = as.character(str_glue("{x}.Status"))) %>%
                mutate(time = time) %>%
                filter(time > 0) %>%
                filter(Sample.Type == "Tumor") %>%
                rename(sample = Sample)

            rownames(data_list[["data_clinical"]]) <- NULL

            data_exprs <- data_list[["data_exprs"]] %>% as.data.frame()
            data_clinical <- data_list[["data_clinical"]] %>% as.data.frame()

            common_sample <- intersect(colnames(data_exprs), data_clinical %>% pull(sample))
            common_gene <- intersect(coef_file %>% pull(symbol), rownames(data_exprs))

            if (length(common_gene) >= 2) {
                vali <- KM_ROC_curve(
                    model_coef = coef_file, exp = data_exprs[, common_sample],
                    clinical = data_clinical %>% filter(sample %in% common_sample),
                    surtime_unit = c(365), saveplot = T, output_dir = od, var_name = cohort_name_status_type,
                    ROC_time_break = c(1, 3, 5), best_cut = F, do_ROC_CI = F, savetiff = F
                )

                # write_tsv(x = vali[[3]], file = sprintf("%s/%s_score_res.tsv", od, cohort_name_status_type), quote = "none")

                vali[[4]]$data_cohort <- cohort_name_status_type
                vali[[4]]$geneNumInVali <- length(common_gene)

                p_auc_inofr <- vali[[4]]
            } else {
                p_auc_inofr <- tibble()
            }
        } else {
            df_tmp <- tibble()
        }
    })

    return(vali_infor)
})
